using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Excel;
using Admin.NET.Application.Service;
using Admin.NET.Core;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Magicodes.ExporterAndImporter.Core.Models;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Yitter.IdGenerator;

namespace Admin.NET.Application;

/// <summary>
/// 房间管理
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class RoomService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<Room> _rep;

	private readonly SqlSugarRepository<RoomBalanceRecord> _balanceRep;

	public RoomService(SqlSugarRepository<Room> rep, SqlSugarRepository<RoomBalanceRecord> balanceRep)
	{
		_rep = rep;
		_balanceRep = balanceRep;
	}

	/// <summary>
	/// 分页查询房间
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/room/page")]
	public async Task<dynamic> Page([FromQuery] RoomInput input)
	{
		List<long> ownerIds = new List<long>();
		if (!string.IsNullOrWhiteSpace(input.OwnerName) || !string.IsNullOrWhiteSpace(input.OwnerAccount))
		{
			ownerIds = await (from u in _rep.Context.Queryable<Owner>().WhereIF(!string.IsNullOrWhiteSpace(input.OwnerName), (Owner u) => u.Name.Contains(input.OwnerName.Trim())).WhereIF(!string.IsNullOrWhiteSpace(input.OwnerAccount), (Owner u) => u.PhoneNumber.Contains(input.OwnerAccount.Trim()))
				select u.Id).ToListAsync();
		}
		List<long> buildingIds = await CommonUtils.GetBuildingIds(_rep.Context, input.BuildingId, input.IsIncludeSub);
		ISugarQueryable<Room> query = _rep.Context.Queryable<Room>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (Room u) => u.Name.Contains(input.Name.Trim())).WhereIF(input.BuildingId.HasValue && input.IsIncludeSub, (Room u) => buildingIds.Contains(u.BuildingId))
			.WhereIF(input.BuildingId.HasValue && !input.IsIncludeSub, (Room u) => (long?)u.BuildingId == input.BuildingId)
			.WhereIF(input.RoomId.HasValue, (Room u) => (long?)u.Id == input.RoomId)
			.WhereIF(input.WarningRuleId.HasValue, (Room u) => u.WarningRuleId == input.WarningRuleId)
			.WhereIF(!string.IsNullOrWhiteSpace(input.OwnerName) || !string.IsNullOrWhiteSpace(input.OwnerAccount), (Room u) => u.OwnerId != null && ownerIds.Contains((long)u.OwnerId))
			.WhereIF(!string.IsNullOrWhiteSpace(input.Remark), (Room u) => u.Remark.Contains(input.Remark.Trim()));
		query = query.OrderBuilder(input);
		return await query.Select((Room s) => new RoomOutput
		{
			Name = s.Name,
			BuildingId = s.BuildingId,
			Area = s.Area,
			Balance = s.Balance,
			BuildingName = from s1 in SqlFunc.Subqueryable<Building>()
				where s1.Id == s.BuildingId
				select s1.Name,
			CreateTime = s.CreateTime,
			CreateUserId = s.CreateUserId,
			Id = s.Id,
			IsDelete = s.IsDelete,
			OwnerId = s.OwnerId,
			UpdateTime = s.UpdateTime,
			UpdateUserId = s.UpdateUserId,
			Remark = s.Remark,
			LatestWarningBalance = s.LatestWarningBalance,
			WarningRuleId = s.WarningRuleId,
			WarningRuleName = from s4 in SqlFunc.Subqueryable<WarningRule>()
				where (long?)s4.Id == s.WarningRuleId
				select s4.Name,
			OwnerName = from s2 in SqlFunc.Subqueryable<Owner>()
				where (long?)s2.Id == s.OwnerId
				select s2.Name,
			OwnerAccount = from s3 in SqlFunc.Subqueryable<Owner>()
				where (long?)s3.Id == s.OwnerId
				select s3.PhoneNumber
		}).ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 导出列表excel
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/room/templeteexcel")]
	public async Task<IActionResult> Templeteexcel()
	{
		string str = "房间模板-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> list = new List<string> { "区域", "房间号", "面积", "预警规则" };
		Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
		List<string> info = (await (from u in _rep.Context.Queryable<WarningRule>()
			select new { u.Name, u.Id }).ToListAsync()).Select(u => u.Name + "  -" + u.Id).ToList();
		List<string> buildingInfo = (await (from u in _rep.Context.Queryable<Building>()
			select new { u.Name, u.Id }).ToListAsync()).Select(u => u.Name + "  -" + u.Id).ToList();
		dic.Add("预警规则", info);
		dic.Add("区域", buildingInfo);
		ExcelUtil excelUtil = new ExcelUtil();
		MemoryStream stream = excelUtil.GetTemplate(list, dic, str);
		return new FileStreamResult(new MemoryStream(stream.ToArray()), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}

	[HttpPost("/room/roomExecl")]
	public async Task<IActionResult> ExportRoom([FromBody] RoomInput input)
	{
		string str = "房间导出-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> column = new List<string>();
		List<string> title = new List<string>();
		ISugarQueryable<Room> query = _rep.Context.Queryable<Room>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (Room u) => u.Name.Contains(input.Name.Trim())).WhereIF(input.BuildingId.HasValue, (Room u) => (long?)u.BuildingId == input.BuildingId);
		query = query.OrderBuilder(input);
		List<RoomOutput> list = await query.Select((Room s) => new RoomOutput
		{
			Name = s.Name,
			BuildingId = s.BuildingId,
			Area = s.Area,
			Balance = s.Balance,
			BuildingName = from s1 in SqlFunc.Subqueryable<Building>()
				where s1.Id == s.BuildingId
				select s1.Name,
			CreateTime = s.CreateTime,
			CreateUserId = s.CreateUserId,
			Id = s.Id,
			IsDelete = s.IsDelete,
			OwnerId = s.OwnerId,
			UpdateTime = s.UpdateTime,
			UpdateUserId = s.UpdateUserId,
			Remark = s.Remark,
			LatestWarningBalance = s.LatestWarningBalance,
			WarningRuleId = s.WarningRuleId,
			WarningRuleName = from s4 in SqlFunc.Subqueryable<WarningRule>()
				where (long?)s4.Id == s.WarningRuleId
				select s4.Name,
			OwnerName = from s2 in SqlFunc.Subqueryable<Owner>()
				where (long?)s2.Id == s.OwnerId
				select s2.Name,
			OwnerAccount = from s3 in SqlFunc.Subqueryable<Owner>()
				where (long?)s3.Id == s.OwnerId
				select s3.PhoneNumber
		}).ToListAsync();
		column.AddRange(new string[8] { "BuildingName", "Name", "Area", "WarningRuleName", "Balance", "OwnerName", "OwnerAccount", "Remark" });
		title.AddRange(new string[8] { "区域", "房间名称", "面积(㎡)", "预警", "余额(￥)", "业主名称", "联系方式", "备注" });
		MemoryStream memery = ExportToExcel.ExportToList(list.ToArray(), str, str, column.ToArray(), title.ToArray());
		App.HttpContext.Response.ContentType = "application/vnd.ms-excel";
		byte[] aa = memery.ToArray();
		return new FileStreamResult(new MemoryStream(aa), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}

	/// <summary>
	/// 上传文件
	/// </summary>
	/// <param name="file"></param>
	/// <param name="path"></param>
	/// <returns></returns>
	[HttpPost("/room/uploadpdf")]
	public async Task UploadFile([Required] IFormFile file, string path = "")
	{
		try
		{
			ExcelUtil excelUtil = new ExcelUtil();
			List<AddExcelRoomInput> list = excelUtil.ExcelToList<AddExcelRoomInput>(file, new Dictionary<string, string>
			{
				{ "区域", "Building" },
				{ "房间号", "Name" },
				{ "面积", "Area" },
				{ "预警规则", "WarnningRule" },
				{ "备注", "Remark" }
			});
			List<AddRoomInput> listadd = new List<AddRoomInput>();
			await GetExeleModel(list, listadd);
			List<Room> addInfo = listadd.Adapt<List<Room>>();
			await _rep.Context.Ado.BeginTranAsync();
			_rep.InsertRange(addInfo.ToArray());
			await _rep.Context.Ado.CommitTranAsync();
		}
		catch (Exception ex)
		{
			await _rep.Context.Ado.RollbackTranAsync();
			throw ex;
		}
	}

	private async Task GetExeleModel(List<AddExcelRoomInput> list, List<AddRoomInput> listadd)
	{
		List<long> warningRuleIds = await (from u in _rep.Context.Queryable<WarningRule>()
			select u.Id).ToListAsync();
		List<long> buildingIds = await (from u in _rep.Context.Queryable<Building>()
			select u.Id).ToListAsync();
		foreach (AddExcelRoomInput item in list)
		{
			AddRoomInput addElectricMeterInput = new AddRoomInput
			{
				Name = item.Name
			};
			if (string.IsNullOrEmpty(item.Name))
			{
				throw Oops.Oh("房间号不可为空，请仔细检查");
			}
			addElectricMeterInput.Area = item.Area;
			addElectricMeterInput.Remark = item.Remark;
			if (string.IsNullOrEmpty(item.Building))
			{
				throw Oops.Bah("请为房间号(" + item.Name + ")选择区域");
			}
			long buildingId = Convert.ToInt64(item.Building.Split("-")[1]);
			if (!buildingIds.Contains(buildingId))
			{
				throw Oops.Bah("房间号(" + item.Name + ")区域异常，请仔细核对或重新下载模板");
			}
			addElectricMeterInput.BuildingId = buildingId;
			if (!string.IsNullOrWhiteSpace(item.WarnningRule) && item.WarnningRule.Split("-").Length == 2)
			{
				long ruleId = Convert.ToInt64(item.WarnningRule.Split("-")[1]);
				if (!warningRuleIds.Contains(ruleId))
				{
					throw Oops.Bah("房间号(" + item.Name + ")预警规则异常，请仔细核对或重新下载模板");
				}
				addElectricMeterInput.WarningRuleId = ruleId;
			}
			listadd.Add(addElectricMeterInput);
		}
	}

	[HttpPost("/room/offlinePayExecl")]
	public async Task<IActionResult> OfflinePayExecl([FromBody] RoomInput input)
	{
		string str = "线下退款-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> column = new List<string>();
		List<string> title = new List<string>();
		ISugarQueryable<Room> query = _rep.Context.Queryable<Room>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (Room u) => u.Name.Contains(input.Name.Trim())).WhereIF(input.BuildingId.HasValue, (Room u) => (long?)u.BuildingId == input.BuildingId);
		query = query.OrderBuilder(input);
		List<RoomOutput> list = await query.Select((Room s) => new RoomOutput
		{
			Name = s.Name,
			BuildingId = s.BuildingId,
			Area = s.Area,
			Balance = s.Balance,
			BuildingName = from s1 in SqlFunc.Subqueryable<Building>()
				where s1.Id == s.BuildingId
				select s1.Name,
			CreateTime = s.CreateTime,
			CreateUserId = s.CreateUserId,
			Id = s.Id,
			IsDelete = s.IsDelete,
			OwnerId = s.OwnerId,
			UpdateTime = s.UpdateTime,
			UpdateUserId = s.UpdateUserId,
			Remark = s.Remark,
			LatestWarningBalance = s.LatestWarningBalance,
			WarningRuleId = s.WarningRuleId,
			WarningRuleName = from s4 in SqlFunc.Subqueryable<WarningRule>()
				where (long?)s4.Id == s.WarningRuleId
				select s4.Name,
			OwnerName = from s2 in SqlFunc.Subqueryable<Owner>()
				where (long?)s2.Id == s.OwnerId
				select s2.Name,
			OwnerAccount = from s3 in SqlFunc.Subqueryable<Owner>()
				where (long?)s3.Id == s.OwnerId
				select s3.PhoneNumber
		}).ToListAsync();
		column.AddRange(new string[8] { "BuildingName", "Name", "Area", "WarningRuleName", "Balance", "OwnerName", "OwnerAccount", "Remark" });
		title.AddRange(new string[8] { "区域", "房间名称", "面积(㎡)", "预警", "余额(￥)", "业主名称", "联系方式", "备注" });
		MemoryStream memery = ExportToExcel.ExportToList(list.ToArray(), str, str, column.ToArray(), title.ToArray());
		App.HttpContext.Response.ContentType = "application/vnd.ms-excel";
		byte[] aa = memery.ToArray();
		return new FileStreamResult(new MemoryStream(aa), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}

	/// <summary>
	/// 增加房间
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/room/add")]
	public async Task Add(AddRoomInput input)
	{
		Room entity = input.Adapt<Room>();
		if (await (from w in _rep.Context.Queryable<Room>()
			where w.BuildingId == entity.BuildingId && w.Name == entity.Name.Trim()
			select w).AnyAsync())
		{
			throw Oops.Bah("同一区域，房间名称不可重复");
		}
		await _rep.InsertAsync(entity);
	}

	/// <summary>
	/// 删除房间
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/room/delete")]
	public async Task Delete(DeleteRoomInput input)
	{
		Room entity = await _rep.GetFirstAsync((Room u) => u.Id == input.Id);
		if (entity != null)
		{
			if (entity.OwnerId.HasValue)
			{
				throw Oops.Bah("请先解绑业主再进行操作");
			}
			await _rep.DeleteAsync(entity);
		}
	}

	/// <summary>
	/// 更新房间
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/room/edit")]
	public async Task Update(UpdateRoomInput input)
	{
		Room entity = input.Adapt<Room>();
		await _rep.Context.Updateable(entity).UpdateColumns((Room it) => new { it.Name, it.BuildingId, it.Area, it.WarningRuleId, it.Remark }).ExecuteCommandAsync();
	}

	/// <summary>
	/// 获取房间详细
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/room/detail")]
	public async Task<Room> Get([FromQuery] QueryeRoomInput input)
	{
		return await _rep.GetFirstAsync((Room u) => u.Id == input.Id);
	}

	/// <summary>
	/// 获取房间列表
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/room/list")]
	public async Task<dynamic> List([FromQuery] RoomInput input)
	{
		return await _rep.AsQueryable().ToListAsync();
	}

	/// <summary>
	/// 获取房间列表
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/room/list/{buildingId}")]
	public async Task<dynamic> List(long buildingId)
	{
		return await (from w in _rep.AsQueryable()
			where w.BuildingId == buildingId
			select w).ToListAsync();
	}

	/// <summary>
	/// 获取所有房间递归显示
	/// </summary>
	/// <returns></returns>
	[HttpGet("/room/getallroomswithbuilding")]
	public async Task<dynamic> GetAllRoomsWithBuilding()
	{
		List<Building> buildings = await _rep.Context.Queryable<Building>().ToListAsync();
		List<Room> rooms = await _rep.AsQueryable().ToListAsync();
		List<BuildingRoomOutput> roots = (from w in buildings
			where w.Pid == 0
			select new BuildingRoomOutput
			{
				BuildingId = w.Id,
				BuildingName = w.Name,
				Disabled = false,
				Children = new List<BuildingRoomOutput>(),
				Id = w.Id,
				Label = w.Name
			}).ToList();
		List<long> ids = new List<long>();
		foreach (BuildingRoomOutput item in roots)
		{
			MapBuildingAndRoom(item, buildings, rooms, ids);
		}
		return roots;
	}

	private void MapBuildingAndRoom(BuildingRoomOutput item, List<Building> buildings, List<Room> rooms, List<long> ids)
	{
		if (ids.Contains(item.Id))
		{
			return;
		}
		ids.Add(item.Id);
		item.Children = new List<BuildingRoomOutput>();
		List<BuildingRoomOutput> children = (from w in buildings
			where w.Pid == item.Id
			select new BuildingRoomOutput
			{
				BuildingId = w.Id,
				BuildingName = w.Name,
				Disabled = false,
				Children = new List<BuildingRoomOutput>(),
				Id = w.Id,
				Label = w.Name
			}).ToList();
		if (children.Count > 0)
		{
			item.Children.AddRange(children);
			foreach (BuildingRoomOutput child in children)
			{
				MapBuildingAndRoom(child, buildings, rooms, ids);
			}
		}
		List<BuildingRoomOutput> childrooms = (from w in rooms
			where w.BuildingId == item.Id
			select new BuildingRoomOutput
			{
				BuildingId = w.BuildingId,
				Children = new List<BuildingRoomOutput>(),
				Disabled = false,
				Id = w.Id,
				Label = w.Name,
				RoomArea = w.Area,
				RoomId = w.Id,
				BuildingName = item.BuildingName,
				RoomName = w.Name
			}).ToList();
		if (childrooms.Count > 0)
		{
			item.Children.AddRange(childrooms);
		}
	}

	/// <summary>
	/// 添加房间余额记录
	/// </summary>
	/// <param name="roomId">房间id</param>
	/// <param name="recordId">记录id</param>
	/// <param name="type">类型:0,充值退款记录，1水电结算记录，2自定义账单记录</param>
	/// <param name="amount">金额</param>
	/// <param name="tenantId">租户id</param>
	/// <param name="remark">备注</param>
	/// <returns></returns>
	public async Task AddRoomBalanceRecord(ISqlSugarClient db2, long roomId, long recordId, int type, decimal amount, long tenantId, string remark = null)
	{
		RoomBalanceRecord record = new RoomBalanceRecord
		{
			RoomId = roomId,
			RecordId = recordId,
			Type = type,
			Amount = amount,
			Remark = remark,
			TenantId = tenantId
		};
		await db2.Insertable(record).ExecuteCommandAsync();
	}

	/// <summary>
	/// 获取房间的余额流水记录
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/room/getroombalancerecord")]
	public async Task<dynamic> GetRoomBalanceRecord([FromQuery] RoomBalanceRecordInput input)
	{
		DateTime? endTime = input.EndTime;
		if (input.EndTime.HasValue)
		{
			endTime = endTime?.AddDays(1.0).Date;
		}
		ISugarQueryable<RoomBalanceRecord> query = (from u in _balanceRep.Context.Queryable<RoomBalanceRecord>()
			where u.RoomId == input.RoomId
			select u).WhereIF(input.BeginTime.HasValue, (RoomBalanceRecord u) => u.CreateTime >= input.BeginTime).WhereIF(input.EndTime.HasValue, (RoomBalanceRecord u) => u.CreateTime <= endTime).WhereIF(input.Type.HasValue, (RoomBalanceRecord u) => (int?)u.Type == input.Type);
		query = query.OrderBuilder(input);
		return await query.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 生成房间导入模板
	/// </summary>
	[HttpGet("/room/generateroomexceltemplate")]
	public async Task<IActionResult> GenerateRoomExcelTemplate()
	{
		IExcelImporter Importer = new ExcelImporter();
		byte[] result = await Importer.GenerateTemplateBytes<ImportRoomDto>();
		string fileName = "房间导入模板-" + DateTime.Now.ToString("yyyyMMddHHmmss");
		return new FileStreamResult(new MemoryStream(result), "application/octet-stream")
		{
			FileDownloadName = fileName + ".xlsx"
		};
	}

	[HttpPost("/room/downloadroomexceltemplate")]
	public async Task<IActionResult> DownloadRoomExcelTemplate()
	{
		string filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "ExcelTemplates", "房间导入模板.xlsx");
		byte[] bytes = File.ReadAllBytes(filePath);
		string fileName = "房间导入模板-" + DateTime.Now.ToString("yyyyMMddHHmmss");
		return new FileStreamResult(new MemoryStream(bytes), "application/octet-stream")
		{
			FileDownloadName = fileName + ".xlsx"
		};
	}

	[HttpPost("/room/importroom")]
	[UnitOfWork]
	public async Task ImportRoom([Required] IFormFile file)
	{
		IExcelImporter Importer = new ExcelImporter();
		ImportResult<ImportRoomDto> import = await Importer.Import<ImportRoomDto>(file.OpenReadStream());
		if (import.HasError)
		{
			throw Oops.Bah("导入数据存在错误，请核对");
		}
		if (import.Data.Count == 0)
		{
			throw Oops.Bah("导入数据为空，请核对");
		}
		List<Building> regions = await _rep.Context.Queryable<Building>().ToTreeAsync((Building it) => it.Children, (Building it) => it.Pid, 0, (Building it) => it.Id);
		List<WarningRule> warningRules = await _rep.Context.Queryable<WarningRule>().ToListAsync();
		List<Room> allRooms = await _rep.Context.Queryable<Room>().ToListAsync();
		List<Building> newBuildings = new List<Building>();
		List<Room> newRooms = new List<Room>();
		foreach (ImportRoomDto item in import.Data)
		{
			if (string.IsNullOrWhiteSpace(item.Name))
			{
				throw Oops.Bah("存在无效房间名称，请核对后重新导入");
			}
			long buildingId = 0L;
			Building region1 = regions.Where((Building w) => w.Name == item.Region1.Trim()).FirstOrDefault();
			if (region1 != null)
			{
				buildingId = region1.Id;
				if (!string.IsNullOrWhiteSpace(item.Region2))
				{
					Building region2 = region1.Children.Where((Building w) => w.Name == item.Region2.Trim()).FirstOrDefault();
					if (region2 != null)
					{
						buildingId = region2.Id;
						if (!string.IsNullOrWhiteSpace(item.Region3))
						{
							Building region3 = region2.Children.Where((Building w) => w.Name == item.Region3.Trim()).FirstOrDefault();
							if (region3 != null)
							{
								buildingId = region3.Id;
								if (!string.IsNullOrWhiteSpace(item.Region4))
								{
									Building region4 = region3.Children.Where((Building w) => w.Name == item.Region4.Trim()).FirstOrDefault();
									if (region4 != null)
									{
										buildingId = region4.Id;
										if (!string.IsNullOrWhiteSpace(item.Region5))
										{
											Building region5 = region4.Children.Where((Building w) => w.Name == item.Region5.Trim()).FirstOrDefault();
											if (region5 != null)
											{
												buildingId = region5.Id;
											}
											else
											{
												Building building5 = new Building
												{
													Id = YitIdHelper.NextId(),
													Name = item.Region5.Trim(),
													Pid = region4.Id,
													Children = new List<Building>()
												};
												newBuildings.Add(building5);
												region4.Children.Add(building5);
												buildingId = building5.Id;
											}
										}
									}
									else
									{
										Building building4 = new Building
										{
											Id = YitIdHelper.NextId(),
											Name = item.Region4.Trim(),
											Pid = region3.Id,
											Children = new List<Building>()
										};
										newBuildings.Add(building4);
										region3.Children.Add(building4);
										buildingId = building4.Id;
										if (!string.IsNullOrWhiteSpace(item.Region5))
										{
											Building building5 = new Building
											{
												Id = YitIdHelper.NextId(),
												Name = item.Region5.Trim(),
												Pid = building4.Id,
												Children = new List<Building>()
											};
											newBuildings.Add(building5);
											building4.Children.Add(building5);
											buildingId = building5.Id;
										}
									}
								}
							}
							else
							{
								Building building3 = new Building
								{
									Id = YitIdHelper.NextId(),
									Name = item.Region3.Trim(),
									Pid = region2.Id,
									Children = new List<Building>()
								};
								newBuildings.Add(building3);
								region2.Children.Add(building3);
								buildingId = building3.Id;
								if (!string.IsNullOrWhiteSpace(item.Region4))
								{
									Building building4 = new Building
									{
										Id = YitIdHelper.NextId(),
										Name = item.Region4.Trim(),
										Pid = building3.Id,
										Children = new List<Building>()
									};
									newBuildings.Add(building4);
									building3.Children.Add(building4);
									buildingId = building4.Id;
									if (!string.IsNullOrWhiteSpace(item.Region5))
									{
										Building building5 = new Building
										{
											Id = YitIdHelper.NextId(),
											Name = item.Region5.Trim(),
											Pid = building4.Id,
											Children = new List<Building>()
										};
										newBuildings.Add(building5);
										building4.Children.Add(building5);
										buildingId = building5.Id;
									}
								}
							}
						}
					}
					else
					{
						Building building2 = new Building
						{
							Id = YitIdHelper.NextId(),
							Name = item.Region2.Trim(),
							Pid = region1.Id,
							Children = new List<Building>()
						};
						newBuildings.Add(building2);
						region1.Children.Add(building2);
						buildingId = building2.Id;
						if (!string.IsNullOrWhiteSpace(item.Region3))
						{
							Building building3 = new Building
							{
								Id = YitIdHelper.NextId(),
								Name = item.Region3.Trim(),
								Pid = building2.Id,
								Children = new List<Building>()
							};
							newBuildings.Add(building3);
							building2.Children.Add(building3);
							buildingId = building3.Id;
							if (!string.IsNullOrWhiteSpace(item.Region4))
							{
								Building building4 = new Building
								{
									Id = YitIdHelper.NextId(),
									Name = item.Region4.Trim(),
									Pid = building3.Id,
									Children = new List<Building>()
								};
								newBuildings.Add(building4);
								building3.Children.Add(building4);
								buildingId = building4.Id;
								if (!string.IsNullOrWhiteSpace(item.Region5))
								{
									Building building5 = new Building
									{
										Id = YitIdHelper.NextId(),
										Name = item.Region5.Trim(),
										Pid = building4.Id,
										Children = new List<Building>()
									};
									newBuildings.Add(building5);
									building4.Children.Add(building5);
									buildingId = building5.Id;
								}
							}
						}
					}
				}
			}
			else
			{
				Building building1 = new Building
				{
					Id = YitIdHelper.NextId(),
					Name = item.Region1.Trim(),
					Pid = 0L,
					Children = new List<Building>()
				};
				newBuildings.Add(building1);
				regions.Add(building1);
				buildingId = building1.Id;
				if (!string.IsNullOrWhiteSpace(item.Region2))
				{
					Building building2 = new Building
					{
						Id = YitIdHelper.NextId(),
						Name = item.Region2.Trim(),
						Pid = building1.Id,
						Children = new List<Building>()
					};
					newBuildings.Add(building2);
					building1.Children.Add(building2);
					buildingId = building2.Id;
					if (!string.IsNullOrWhiteSpace(item.Region3))
					{
						Building building3 = new Building
						{
							Id = YitIdHelper.NextId(),
							Name = item.Region3.Trim(),
							Pid = building2.Id,
							Children = new List<Building>()
						};
						newBuildings.Add(building3);
						building2.Children.Add(building3);
						buildingId = building3.Id;
						if (!string.IsNullOrWhiteSpace(item.Region4))
						{
							Building building4 = new Building
							{
								Id = YitIdHelper.NextId(),
								Name = item.Region4.Trim(),
								Pid = building3.Id,
								Children = new List<Building>()
							};
							newBuildings.Add(building4);
							building3.Children.Add(building4);
							buildingId = building4.Id;
							if (!string.IsNullOrWhiteSpace(item.Region5))
							{
								Building building5 = new Building
								{
									Id = YitIdHelper.NextId(),
									Name = item.Region5.Trim(),
									Pid = building4.Id,
									Children = new List<Building>()
								};
								newBuildings.Add(building5);
								building4.Children.Add(building5);
								buildingId = building5.Id;
							}
						}
					}
				}
			}
			if (buildingId == 0L && newBuildings.Count > 0)
			{
				throw Oops.Bah("区域id异常");
			}
			Room tmproom = allRooms.Where((Room w) => w.Name == item.Name.Trim() && w.BuildingId == buildingId).FirstOrDefault();
			if (tmproom != null)
			{
				throw Oops.Bah($"{item.Region1}/{item.Region2}/{item.Region3}/{item.Region4}/{item.Region5}/{item.Name}:数据已存在，请删除后重新导入");
			}
			Room room1 = new Room
			{
				Name = item.Name.Trim(),
				Area = item.Area.GetValueOrDefault(),
				BuildingId = buildingId
			};
			if (!string.IsNullOrWhiteSpace(item.WarningRule))
			{
				WarningRule warning = warningRules.Where((WarningRule w) => w.Name == item.WarningRule.Trim()).FirstOrDefault();
				if (warning == null)
				{
					throw Oops.Bah("预警规则请与系统录入保持一致或不填写：" + item.WarningRule);
				}
				room1.WarningRuleId = warning.Id;
			}
			newRooms.Add(room1);
		}
		await _rep.Context.Insertable(newBuildings).ExecuteCommandAsync();
		await _rep.Context.Insertable(newRooms).ExecuteCommandAsync();
	}
}
